/**
 * Module dependencies.
 */

var express = require('express'),
	https = require('https'),
	fs = require('fs'),
	routes = require('./routes'),
	user = require('./routes/user'),
	temperature = require('./routes/temperature'),
	googlecalendar = require('./routes/googlecalendar'),
	teachin = require('./routes/teachin.js'),
	morning = require('./routes/morning.js'),
	security = require('./routes/security.js'),
	notifications = require('./routes/notifications'),
	modulesmanagement = require('./routes/modulesmanagement'),
	config = require('../config'),
	http = require('http'),
	path = require('path'),
	userManager = require('../core/user_manager.js'),
	log = require('../core/log.js');
	

var app = express();

app.configure(function() {
	app.set('port', process.env.PORT || config.server_port);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'jade');
	app.use(express.basicAuth(userManager.log_user)); // basic http auth
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function() {
	app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/temperature/lastOne/:id', temperature.lastOne);
app.get('/temperature/last24h/:id', temperature.last24h);
app.get('/teachin/outlet', teachin.teachinOutlet);
app.get('/teachin/:type', teachin.teachin);
app.all('/authenticationGoogle', googlecalendar.authenticationGoogle);
app.all('/calendar', googlecalendar.printCalendar);

// Android notifications
app.post('/notifications/register', notifications.register);
app.post('/notifications/unregister', notifications.unregister);
app.get('/notifications/notify', notifications.notify);
app.get('/notifications/form', notifications.form);

// Modules management
app.get('/modules/:moduleName/sources', modulesmanagement.getSources);
app.get('/modules/form', modulesmanagement.form);
app.put('/modules/:moduleName', modulesmanagement.create);
app.get('/modules', modulesmanagement.listModules)

// Morning routes
app.get('/morning/config/:id', morning.getMorningConf);
app.put('/morning/config/:id', morning.putMorningConf);

// Security routes
app.get('/security/config/:id', security.getSecurityConf);
app.put('/security/config/:id', security.putSecurityConf); // ":id" matches to "req.params.id" inside the callback (defaults to {})

function start() {
	var options = {
		key: fs.readFileSync(__dirname + '/server-key.pem'),
  		cert: fs.readFileSync(__dirname + '/server-cert.pem'),
  		'passphrase': 'ghome'
	};
	https.createServer(options, app).listen(app.get('port'), function() {
		log.info("web server", "listening on port " + app.get('port') + "...");
	});
}

exports.start = start;

